﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using orm.efcore.api.Entities;

namespace orm.efcore.api.Controllers
{
    /// <summary>
    /// 单表操作
    /// </summary>
    public class SingleController(CoreDbContext dbContext) : EfCoreBaseController(dbContext)
    {
        [HttpPost]
        public async Task<IActionResult> Insert()
        {
            var order = new Order
            {
                Number = DateTime.Now.ToString("yyyyMMddHHmmss"),
                CreateTime = DateTime.Now
            };

            DbContext.Add(order);
            await DbContext.SaveChangesAsync();

            return Ok("Id：" + order.Id);
        }

        [HttpPatch]
        public async Task<IActionResult> Update(int id)
        {
            // 方法一：因为配置了查询默认不跟踪实体，修改时强制跟踪一下
            var order = await DbContext.Order
                .AsTracking()
                .SingleOrDefaultAsync(o => o.Id == id);

            if (order != null)
            {
                order.Number = DateTime.Now.ToString("yyyyMMddHHmmss");
                order.TotalPrice = 1;
                order.CreateTime = DateTime.Now;

                //DbContext.Update(order); // 方法二：或者不跟踪调用一下 Update
                return Ok(await DbContext.SaveChangesAsync() > 0);
            }

            return NotFound();
        }

        [HttpDelete]
        public async Task<IActionResult> Delete(int id)
        {
            return Ok(await DbContext.Order
                .Where(o => o.Id == id)
                .ExecuteDeleteAsync() > 0);
        }

        [HttpGet]
        public async Task<IActionResult> PageList(int pageIndex, int pageSize)
        {
            int skip = (pageIndex - 1) * pageSize;
            var query = DbContext.Order.Where(o => o.IsDeleted == false);
            var rows = await query
                .OrderByDescending(o => o.Id)
                .Skip(skip)
                .Take(pageSize)
                .ToListAsync();

            int total = await query.CountAsync();
            return Ok(new { rows, total });
        }

        [HttpGet]
        public async Task<IActionResult> Detail(int id)
        {
            return Ok(await DbContext.Order.FindAsync(id));
        }
    }
}
